from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

# Create your views here.
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializers


class QQLoginUrlView(APIView):
    '''
        构建跳转链接
    '''
    def get(self,request):
        state = request.query_params.get('next')
        if state is None:
            state = '/'

        # 1,生成qq对象  初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,state=state)

        # 2,获取QQ登录扫码页面，扫码后得到Authorization Code
        login_url = oauth.get_qq_url()

        # 5,返回url
        return Response({'login_url':login_url})


class OauthView(CreateAPIView):
    '''
        获取openid和绑定openid
    '''
    # 第一种方式,直接继承的方式
    serializer_class = OauthSerializers

    def get(self,request):

        # 1,获取code值
        code = request.query_params.get('code')
        if code is None:
            return Response({'errors':'code值不能为空'},status=400)

        # 2,通过Authorization Code值获取Access Token
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state='/')
        access_token = oauth.get_access_token(code)

        # 3,通过Access Token获取OpenID
        openid = oauth.get_open_id(access_token)

        # 4,判断openid与美多用户是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 返回加密的openid
            tjs = TJS(settings.SECRET_KEY,300)
            data = tjs.dumps({'openid':openid}).decode()

            return Response({'access_token':data})

            # 5,未绑定,绑定openid
        else:
            # 6,如果绑定成功则登陆
            user = qq_user.user

            # 生成jwk token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })

            #合并购物车操作
            response = merge_cart_cookie_to_redis(request,response,user)
            return response


